from flask import Flask, request, jsonify

from scipy.spatial import distance

from news_classification.glda import get_glda_infer_engine, read_glda_phi_file, \
    read_glda_vocab, read_glda_mapv, calculate_glda_doc_generation_prob_vector
from news_classification.utils import cut_doc

app = Flask(__name__)
model_fp = './model/theme-news/glda-256-topics/themes-news-218-topics-lda.model'
inf_engine = get_glda_infer_engine(model_fp)
phi = read_glda_phi_file(model_fp)
word2id = read_glda_vocab(model_fp)
mapv = read_glda_mapv(model_fp)


@app.route('/score-theme-news-by-mapv', methods=['POST'])
def score_article_by_mapv():
    text = request.form['text']
    words = cut_doc(text)
    doc_topic_probs = inf_engine.lda_infer(' '.join(words))
    dgpv = calculate_glda_doc_generation_prob_vector(words, doc_topic_probs, phi, word2id)
    corr = distance.correlation(mapv, dgpv)
    cosine = distance.cosine(mapv, dgpv)
    score = 1 - (corr + cosine) / 2
    if score and score < 0.15:
        result = '舍弃'
    elif not score:
        result = '舍弃'
    else:
        result = '保留'
    return jsonify({'corr-dist': corr, 'cosine-dist': cosine, 'score': score, 'result': result})
